package com.mt.mtyx.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.mt.mtyx.common.auth.AuthContextHolder;
import com.mt.mtyx.common.exception.BusinessException;
import com.mt.mtyx.common.result.Result;
import com.mt.mtyx.common.result.ResultCodeEnum;
import com.mt.mtyx.common.utils.Helper;
import com.mt.mtyx.common.utils.JwtHelper;
import com.mt.mtyx.common.utils.RedisConst;
import com.mt.mtyx.entity.user.User;
import com.mt.mtyx.entity.user.UserLoginLog;
import com.mt.mtyx.enums.UserType;
import com.mt.mtyx.user.service.UserService;
import com.mt.mtyx.user.utils.ConstantPropertiesUtil;
import com.mt.mtyx.user.utils.HttpClientUtils;
import com.mt.mtyx.vo.user.LeaderAddressVo;
import com.mt.mtyx.vo.user.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author WMT
 * @Date 2023/7/28 15:23
 */
@Api(tags = "微信相关接口")
@RestController
@RequestMapping("/api/user/wechat")
public class WechatApiController {

    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @ApiOperation("登录微信")
    @GetMapping("/login/{code}")
    public Result<Map<String, Object>> wechatLogin(@PathVariable String code) {
        Map<String, Object> map = new HashMap<>();
        // 1.得到微信返回临时code
        // 2.通过code + 小程序id(appId) + 小程序秘钥(appSecret) 请求微信接口服务
        String appId = ConstantPropertiesUtil.WX_OPEN_APP_ID;
        String appSecret = ConstantPropertiesUtil.WX_OPEN_APP_SECRET;

        // 拼接请求url
        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s") // %s 类似于占位符
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(url.toString(), appId, appSecret, code);

        // HttpClient发送请求
        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("获取token失败！", ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD.getCode());
        }

        // 3.请求微信接口服务 返回session_key 和 openId(微信唯一标识)
        JSONObject jsonObject = JSONObject.parseObject(result);
        String sessionKey = jsonObject.getString("session_key");
        String openId = jsonObject.getString("openId");

        // 4.添加微信用户信息到数据库
        User user = userService.getByOpenId(openId);
        if (user == null) {
            user = new User();
            user.setOpenId(openId);
            user.setNickName(openId);
            user.setPhotoUrl("");
            user.setUserType(UserType.USER);
            user.setIsNew(0);
            Helper.setBaseProperties(user, LocalDateTime.now());
            userService.save(user);
        }

        // 5.根据userId查询提货点信息和团长信息
        LeaderAddressVo leaderAddressVo = userService.getLeaderAddressByUserId(user.getId());

        // 6.根据userId username 生成JWT
        String token = JwtHelper.createToken(user.getId(), user.getNickName());

        // 7.获取当前用户信息 存到Redis
        UserLoginVo userLoginVo = userService.getUserLoginVo(user.getId());
        redisTemplate.opsForValue()
                .set(RedisConst.USER_LOGIN_KEY_PREFIX + user.getId(),
                        userLoginVo,
                        RedisConst.USERKEY_TIMEOUT,
                        TimeUnit.DAYS);
        // 8.返回封装数据
        map.put("user", user);
        map.put("token", token);
        map.put("leaderAddressVo",leaderAddressVo);
        return Result.success(map);
    }

    @ApiOperation("更新用户信息")
    @PostMapping("/auth/updateUser")
    public Result<Boolean> update(@RequestBody User user) {
        User userDb = userService.getById(AuthContextHolder.getUserId());
        // 把昵称更新为微信用户
        userDb.setNickName(user.getNickName().replaceAll("[ue000-uefff]", "*"));
        userDb.setPhotoUrl(user.getPhotoUrl());
        return Result.success(userService.updateById(userDb));
    }
}
